package com.lgw.coupon.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.lgw.commons.constant.ApiConstant;
import com.lgw.commons.constant.RedisKeyConstant;
import com.lgw.commons.model.domain.ResultInfo;
import com.lgw.commons.model.pojo.Coupon;
import com.lgw.commons.utils.AssertUtil;
import com.lgw.commons.utils.ResultInfoUtil;
import com.lgw.commons.vo.CouponTemplateInfo;
import com.lgw.coupon.mapper.CouponMapper;
import com.lgw.coupon.service.IUserService;
import com.lgw.coupon.vo.AcquireTemplateRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${service.name.coupon-template}")
    private String couponTemplate;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CouponMapper couponMapper;

    @Override
    public ResultInfo findAvailableTemplate(Long customerId) {
        Date cur = new Date();
        //发送请求 请求路径，返回接收类
        System.out.println(couponTemplate + "sdk/all");
        ResponseEntity<ResultInfo> result = restTemplate.getForEntity(
                couponTemplate + "sdk/all",
                ResultInfo.class
        );
        AssertUtil.isTrue(result.getStatusCode() != HttpStatus.OK, "发送请求出现错误");
        ResultInfo resultInfo = result.getBody();
        if (resultInfo.getCode() != ApiConstant.SUCCESS_CODE) {
            //获取可用优惠券模板失败
            resultInfo.setData(resultInfo.getMessage());
            return resultInfo;
        }
        // 获取优惠券模板
        List<CouponTemplateInfo> templateInfos = (ArrayList<CouponTemplateInfo>) resultInfo.getData();
        log.info("可用的优惠券模板数量：{}", templateInfos.size());
        //过滤掉其中可能包含过期的优惠券模板
        String jsonString = JSONUtil.toJsonStr(templateInfos);
        JSONArray object = JSONUtil.parseArray(jsonString);
        List<CouponTemplateInfo> list = JSONUtil.toList(object,CouponTemplateInfo.class);
        log.info("可用的没有过期的优惠券模板数量: {}", list.size());
        return ResultInfoUtil.buildSuccess(request.getServletPath(), list);
    }

    /**
     * 用户领取优惠券
     *
     * @param acquireTemplateRequest
     * @return
     */
    @Override
    public Coupon acquireCoupon(AcquireTemplateRequest acquireTemplateRequest) {

        //尝试获取优惠券码
        String redisKey = RedisKeyConstant.coupon_template_code.getKey() +
                acquireTemplateRequest.getCouponTemplateInfo().getId();
        String couponKey = (String) redisTemplate.opsForList().leftPop(redisKey);
        AssertUtil.isNotEmpty(couponKey, "没有可用的优惠券码");

        Coupon newCoupon = new Coupon(acquireTemplateRequest.getCouponTemplateInfo().getId(),
                acquireTemplateRequest.getConstomerId(),
                couponKey,
                0
        );
        //保存优惠券DB
        couponMapper.save(newCoupon);
        log.info("主键id：{}", newCoupon.getId());

        return newCoupon;
    }
}
